package com.yanqu.road.server.cmd.union.cross;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.enums.eUnionSyncType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manager.user.CrossUserNotifyMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.Objects;

@Cmd(code = Protocol.C_CROSS_UNION_DETAIL, desc = "联盟详细信息")
public class CrossGetUnionDetailCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        CrossUnionProto.UnionDetailCrossReqMsg reqMsg = CrossUnionProto.UnionDetailCrossReqMsg.parseFrom(packet.getBytes());
        CrossUnionMember member = CrossUnionMgr.getUnionMemberByUserId(packet.getPlayerId());
        String unionUid = "";
        if(member != null){
            unionUid = member.getUnionUid();
        }
        UserBaseInfo baseInfo = null;
        if(reqMsg.getPlayerBaseData() != null){
            baseInfo = PlayerBasePb.parseToUserBaseInfo(reqMsg.getPlayerBaseData());
            if(!Objects.equals(unionUid, baseInfo.getUnionUid())){
                baseInfo.setUnionUid(unionUid);
            }
            //Redis修改角色商会信息
            if(ChannelConfig.USER_INFO_USE_REDIS == 1) {
                try {
                    RedisManger.getRedisUtil().setString("user_base_info:" + packet.getPlayerId(), JSON.toJSONString(baseInfo));
                } catch (Exception e) {
                    log.error("update user info to redis fail,userId:{},error:", packet.getPlayerId(), e);
                }
            }
            CrossUserNotifyMgr.notifyReload(baseInfo, packet.getPlayerId());
        }

        MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_UNION_DETAIL, CrossUnionMgr.getUnionDetailMsg(unionUid, eUnionSyncType.Normal.getValue())));

        CrossUnionMgr.judgeChangeUnionOwner(member, unionUid);

        CrossUnionMgr.checkCoolingOffTimeNotice(member);
    }

    @Override
    public void sendData() {

    }
}
